package com.competition.commgr.controller;

import java.util.List;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.competition.commgr.domain.RegistrationReview;
import com.competition.common.utils.PageUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.competition.common.annotation.Log;
import com.competition.common.core.controller.BaseController;
import com.competition.common.core.domain.AjaxResult;
import com.competition.common.enums.BusinessType;
import com.competition.commgr.domain.Award;
import com.competition.commgr.service.IAwardService;
import com.competition.common.utils.poi.ExcelUtil;
import com.competition.common.core.page.TableDataInfo;
import com.competition.common.utils.SecurityUtils;
import com.competition.common.utils.file.FileUploadUtils;
import com.competition.common.config.RuoYiConfig;

/**
 * 获奖记录Controller
 *
 * @author ruoyi
 * @date 2025-05-10
 */
@RestController
@RequestMapping("/commgr/award")
public class AwardController extends BaseController
{
    @Autowired
    private IAwardService awardService;

    /**
     * 查询获奖记录列表
     */
    @PreAuthorize("@ss.hasPermi('commgr:award:list')")
    @GetMapping("/list")
    public TableDataInfo list(Award award)
    {
        startPage();
        List<Award> list = awardService.selectAwardList(award);
        return getDataTable(list);
    }

    /**
     * 导出获奖记录列表
     */
    @PreAuthorize("@ss.hasPermi('commgr:award:export')")
    @Log(title = "获奖记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Award award)
    {
        List<Award> list = awardService.selectAwardList(award);
        ExcelUtil<Award> util = new ExcelUtil<Award>(Award.class);
        util.exportExcel(response, list, "获奖记录数据");
    }

    /**
     * 获取获奖记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('commgr:award:query')")
    @GetMapping(value = "/{awardId}")
    public AjaxResult getInfo(@PathVariable("awardId") Long awardId)
    {
        return success(awardService.selectAwardByAwardId(awardId));
    }

    /**
     * 新增获奖记录
     */
    @PreAuthorize("@ss.hasPermi('commgr:award:add')")
    @Log(title = "获奖记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Award award)
    {
        return toAjax(awardService.insertAward(award));
    }

    /**
     * 修改获奖记录
     */
    @PreAuthorize("@ss.hasPermi('commgr:award:edit')")
    @Log(title = "获奖记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Award award)
    {
        return toAjax(awardService.updateAward(award));
    }

    /**
     * 删除获奖记录
     */
    @PreAuthorize("@ss.hasPermi('commgr:award:remove')")
    @Log(title = "获奖记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{awardIds}")
    public AjaxResult remove(@PathVariable Long[] awardIds)
    {
        return toAjax(awardService.deleteAwardByAwardIds(awardIds));
    }

    // ============== 新增方法 ==============

    /**
     * 检查上报权限
     */
    @PreAuthorize("@ss.hasPermi('commgr:award:add')")
    @GetMapping("/checkPermission")
    public AjaxResult checkPermission(@RequestParam Long teamId)
    {
        Long userId = SecurityUtils.getUserId();
        logger.info("动态用户权限检查 - 用户ID: {}, 团队ID: {}", userId, teamId);
        boolean hasPermission = awardService.checkTeamMembership(userId, teamId);
        return success(hasPermission);
    }

    /**
     * 详细权限检查
     */
    @PreAuthorize("@ss.hasPermi('commgr:award:add')")
    @GetMapping("/checkPermissionDetail")
    public AjaxResult checkPermissionDetail(@RequestParam Long teamId)
    {
        Long userId = SecurityUtils.getUserId();
        logger.info("动态用户详细权限检查 - 用户ID: {}, 团队ID: {}", userId, teamId);

        Map<String, Object> result = new HashMap<>();
        result.put("userId", userId);
        result.put("teamId", teamId);

        // 1. 检查团队成员身份
        boolean isTeamMember = awardService.checkTeamMembership(userId, teamId);
        result.put("isTeamMember", isTeamMember);

        // 2. 检查审核状态
        int approvedCount = awardService.getApprovedTrainingCenterRegistrations(teamId);
        result.put("approvedCount", approvedCount);
        result.put("isApproved", approvedCount > 0);

        // 3. 最终权限结果
        boolean hasPermission = isTeamMember && (approvedCount > 0);
        result.put("hasPermission", hasPermission);

        return success(result);
    }

    /**
     * 获取用户有权限的团队列表
     */
    @PreAuthorize("@ss.hasPermi('commgr:award:add')")
    @GetMapping("/myTeams")
    public AjaxResult getMyTeams()
    {
        Long userId = SecurityUtils.getUserId();
        logger.info("获取动态用户团队列表 - 用户ID: {}", userId);
        List<Award> teamList = awardService.selectUserTeams(userId);
        logger.info("动态用户团队列表结果 - 数量: {}", teamList.size());
        return success(teamList);
    }

    /**
     * 根据团队ID获取赛事信息
     */
    @PreAuthorize("@ss.hasPermi('commgr:award:add')")
    @GetMapping("/competitionInfo")
    public AjaxResult getCompetitionInfo(@RequestParam Long teamId)
    {
        Long userId = SecurityUtils.getUserId();
        logger.info("动态用户获取赛事信息 - 用户ID: {}, 团队ID: {}", userId, teamId);
        Award competitionInfo = awardService.selectCompetitionInfoByTeamId(teamId);
        return success(competitionInfo);
    }

    /**
     * 上报获奖信息（包含文件上传）
     */
    @PreAuthorize("@ss.hasPermi('commgr:award:add')")
    @Log(title = "获奖记录上报", businessType = BusinessType.INSERT)
    @PostMapping("/report")
    public AjaxResult reportAward(@RequestParam("sessionId") Long sessionId,
                                  @RequestParam("teamId") Long teamId,
                                  @RequestParam("level") String level,
                                  @RequestParam("certificateFile") MultipartFile file)
    {
        try {
            Long userId = SecurityUtils.getUserId();
            logger.info("动态用户上报获奖信息 - 用户ID: {}, 团队ID: {}", userId, teamId);

            // 权限校验
            if (!awardService.checkTeamMembership(userId, teamId)) {
                return error("无权限上报或团队未通过审核");
            }

            // 文件校验
            if (!validateCertificateFile(file)) {
                return error("证书文件格式不支持或大小超过5MB");
            }

            // 文件上传
            String filePath = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), file);

            // 创建获奖记录
            Award award = new Award();
            award.setSessionId(sessionId);
            award.setTeamId(teamId);
            award.setLevel(String.valueOf(Long.valueOf(level)));
            award.setCertificate(filePath);

            return toAjax(awardService.insertAward(award));
        } catch (Exception e) {
            logger.error("动态用户上报获奖信息失败", e);
            return error("上报失败：" + e.getMessage());
        }
    }

    /**
     * 检查团队成员身份
     */
    @PreAuthorize("@ss.hasPermi('commgr:award:list')")
    @GetMapping("/checkMembership")
    public AjaxResult checkMembership(@RequestParam Long teamId)
    {
        Long userId = SecurityUtils.getUserId();
        logger.info("动态用户检查团队成员身份 - 用户ID: {}, 团队ID: {}", userId, teamId);
        boolean isMember = awardService.checkTeamMembership(userId, teamId);
        return success(isMember);
    }

    /**
     * 获取获奖等级字典
     */
    @GetMapping("/awardLevels")
    public AjaxResult getAwardLevels()
    {
        return success("获奖等级字典可通过系统字典接口获取");
    }

    /**
     * 调试用户团队数据
     */
    @GetMapping("/debugTeamsDetail")
    public AjaxResult debugTeamsDetail()
    {
        Long userId = SecurityUtils.getUserId();
        logger.info("动态用户调试团队数据 - 用户ID: {}", userId);
        List<Map<String, Object>> debugInfo = (List<Map<String, Object>>) awardService.debugUserTeamsDetail(userId);
        return success(debugInfo);
    }

    // ============== 新增动态用户调试接口 ==============

    /**
     * 获取当前用户信息
     */
    @GetMapping("/currentUser")
    public AjaxResult getCurrentUser() {
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();

        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("userId", userId);
        userInfo.put("userName", userName);
        userInfo.put("loginTime", new java.util.Date());

        logger.info("获取当前动态用户信息 - 用户ID: {}, 用户名: {}", userId, userName);
        return success(userInfo);
    }

    /**
     * 测试动态用户权限
     */
    @GetMapping("/testDynamicPermission")
    public AjaxResult testDynamicPermission(@RequestParam Long teamId) {
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();

        logger.info("=== 动态用户权限测试开始 ===");
        logger.info("测试用户 - ID: {}, 名称: {}", userId, userName);
        logger.info("测试团队 - ID: {}", teamId);

        Map<String, Object> result = new HashMap<>();

        Map<String, Object> userInfoMap = new HashMap<>();
        userInfoMap.put("userId", userId);
        userInfoMap.put("userName", userName);
        result.put("userInfo", userInfoMap);

        result.put("teamId", teamId);

        // 1. 检查团队成员身份
        boolean isTeamMember = awardService.checkTeamMembership(userId, teamId);
        result.put("isTeamMember", isTeamMember);
        logger.info("团队成员检查结果: {}", isTeamMember);

        // 2. 检查审核状态
        int approvedCount = awardService.getApprovedTrainingCenterRegistrations(teamId);
        result.put("approvedCount", approvedCount);
        result.put("isApproved", approvedCount > 0);
        logger.info("审核状态检查结果: {} (数量: {})", approvedCount > 0, approvedCount);

        // 3. 最终权限结果
        boolean hasPermission = isTeamMember && (approvedCount > 0);
        result.put("hasPermission", hasPermission);
        logger.info("最终权限结果: {}", hasPermission);

        logger.info("=== 动态用户权限测试结束 ===");

        return success(result);
    }

    /**
     * 检查动态用户的所有团队
     */
    @GetMapping("/checkAllTeams")
    public AjaxResult checkAllTeams() {
        Long userId = SecurityUtils.getUserId();
        logger.info("检查动态用户所有团队 - 用户ID: {}", userId);

        Map<String, Object> result = new HashMap<>();
        result.put("userId", userId);

        // 获取用户的所有团队关系
        List<Map<String, Object>> allTeams = (List<Map<String, Object>>) awardService.debugUserTeamsDetail(userId);
        result.put("allTeams", allTeams);

        // 获取有权限的团队列表
        List<Award> validTeams = awardService.selectUserTeams(userId);
        result.put("validTeams", validTeams);
        result.put("validTeamCount", validTeams.size());

        logger.info("动态用户团队检查完成 - 总团队数: {}, 有效团队数: {}",
                allTeams.size(), validTeams.size());

        return success(result);
    }

    // ============== 辅助方法 ==============

    /**
     * 验证证书文件
     */
    private boolean validateCertificateFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            return false;
        }

        // 检查文件类型
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            return false;
        }

        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        if (!fileExtension.equals(".png") && !fileExtension.equals(".jpg") && !fileExtension.equals(".jpeg")) {
            return false;
        }

        // 检查文件大小 (5MB)
        long fileSize = file.getSize();
        if (fileSize > 5 * 1024 * 1024) {
            return false;
        }

        return true;
    }

    /**
     * 检查上报权限（包含审核状态检查）
     */
    private boolean checkReportPermission(Long userId, Long teamId) {
        // 检查团队成员身份
        boolean isTeamMember = awardService.checkTeamMembership(userId, teamId);
        if (!isTeamMember) {
            return false;
        }

        // 检查审核状态
        int approvedCount = awardService.getApprovedTrainingCenterRegistrations(teamId);
        return approvedCount > 0;
    }
}